package com.test.entity;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.annotations.Type;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class ExamModel {

    @ManyToMany(cascade = CascadeType.ALL)
    private Set<QuestionModel> questionList = new HashSet<QuestionModel>();

    @NotNull
    @Column(unique = true)
    private String examNumber;

    @NotNull
    @Size(max = 2000)
    private String examDescription;

    @NotNull
    @ManyToOne(fetch = FetchType.EAGER)
    private Profile profile;

    @ManyToOne(fetch = FetchType.EAGER)
    private User user;
    
    @NotNull
    @Type(type="yes_no")
    private Boolean sharedExam;
    
    public static List<ExamModel> findExamModel(int firstResult, int maxResults,Long userId){
    	StringBuffer queryString = new StringBuffer();
    	queryString.append("SELECT o FROM ExamModel o,User u");
    	queryString.append(" Where (o.sharedExam='y'");
    	queryString.append(" or ( o.user.id=:userId and o.sharedExam='n'))");
    	
    	//queryString.append(" or o.user.id=:userId");
    	
    	TypedQuery<ExamModel> query = ExamModel.entityManager().createQuery(queryString.toString(), ExamModel.class);
    	query.setFirstResult(firstResult);
    	query.setMaxResults(maxResults);
    	query.setParameter("userId", userId);
    	
        return query.getResultList();
    	
    }
/*
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Boolean getSharedExam() {
		return sharedExam;
	}

	public void setSharedExam(Boolean sharedExam) {
		this.sharedExam = sharedExam;
	}
  */  
}
